package com.yuqq.token.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuqq.token.domain.LoginUser;
import com.yuqq.token.domain.User;
import com.yuqq.token.mapper.MenuMapper;
import com.yuqq.token.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;


    @Autowired
    private MenuMapper menuMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据用户名查询用户信息
        System.out.println("username:" + username + "-----------------------------------------------");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        System.out.println(user.getUserName() + "ftyguiudfGHJfghjxcfvgh");
//如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名错误");
        }
        List<String> permissionKeyList = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user,permissionKeyList);
//	//测试写法
//		List<String> list = new ArrayList<>(Arrays.asList("test")); return new LoginUser(user,permissionKeyList);
//TODO 根据用户查询权限信息 添加到LoginUser中

//        List<String> list = new ArrayList<>(Arrays.asList("test"));
////封装成UserDetails对象返回
//        return new LoginUser(user, list);
    }
}